package com.ddyx.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.util.StringUtils;

import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;

import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicMatch;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;

/**
 * @ClassName:  RobotscloudUtil   
 * @Description:  萝卜头 人形检测服务
 * @author: JiangShuai 
 * @date:   2018年1月3日 下午4:18:43     
 * @Copyright: 2018 dingdian.parllay.cn Inc. All rights reserved. 
 * 注意：本内容仅限于叮当一下(北京)信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
public class RobotscloudUtil {
	//HmacSHA1加密
	private static final String MAC_NAME = "HmacSHA1";
    private static final String ENC = "UTF-8";
    
    public static void main(String[] args) {
    	String urlStr=PropertiesUtil.getProperty("robotscloud.urlStr");
    	String urlHeader=PropertiesUtil.getProperty("robotscloud.urlHeader");
    	String service_key=PropertiesUtil.getProperty("robotscloud.service_key");
    	String service_key_secret=PropertiesUtil.getProperty("robotscloud.service_key_secret");
    	
    	/*String urlStr="https://api.robotscloud.com/hsr/v3/face_detection";
    	String urlHeader="/hsr/v3/hsr_detection";
    	String service_key="test20171229";
    	String service_key_secret="test20171229servicekeysecret";*/
    	
    	Timestamp time1 = new Timestamp(System.currentTimeMillis()); 
        String timestamp = Long.toString((time1.getTime()/1000));

    	//String localFileName = "D:\\test\\qwew\\2f2a372b-e5e2-499d-b0b7-bfc193cde62f.jpg";
    	String localFileName = "D:\\erweima\\12.png";
    	//String localFileName = "D:\\erweima\\13.jpg";
        String base64str = encode((hamcsha1((urlHeader+"\n"+timestamp).getBytes(), service_key_secret.getBytes()).getBytes()));
        try {
        	String signature=URLEncoder.encode(base64str, ENC);
        	Map<String, String> textMap=new HashMap<String, String>();
        	textMap.put("service_key", service_key);
        	textMap.put("timestamp", timestamp);
            textMap.put("signature", signature);
        	Map<String, String> fileMap=new HashMap<String, String>();
        	fileMap.put("file", localFileName);
        	String ret=formPost(urlStr, textMap, fileMap);
            System.out.println(ret);
            Map<String, String> result=getJsonObject(ret);
            if(StringUtils.hasText(result.get("ret")) && "0".equals(result.get("ret"))) {
            	if("[]".equals(result.get("features"))) {
                	System.out.println("meizhi-123");
                }else {
                	System.out.println("youzhi-1111");
                }
            }
            
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    	
	}
    
    /**
     * @Title: getRobotscloudResult   
     * @Description: 获取 萝卜头 人形检测服务的结果
     * @author: JiangShuai
     * @param: @param localFileName
     * @param: @return  200为ok ,其他为失败   
     * @return: int
     */
    public static Integer getRobotscloudResult(String localFileName) { 
    	String urlStr=PropertiesUtil.getProperty("robotscloud.urlStr");
    	String urlHeader=PropertiesUtil.getProperty("robotscloud.urlHeader");
    	String service_key=PropertiesUtil.getProperty("robotscloud.service_key");
    	String service_key_secret=PropertiesUtil.getProperty("robotscloud.service_key_secret");
    	Timestamp time1 = new Timestamp(System.currentTimeMillis()); 
        String timestamp = Long.toString((time1.getTime()/1000));
        
    	//String localFileName = "D:\\erweima\\13.jpg";
        String base64str = encode((hamcsha1((urlHeader+"\n"+timestamp).getBytes(), service_key_secret.getBytes()).getBytes()));
        try {
        	String signature=URLEncoder.encode(base64str, ENC);
        	Map<String, String> textMap=new HashMap<String, String>();
        	textMap.put("service_key", service_key);
        	textMap.put("timestamp", timestamp);
            textMap.put("signature", signature);
        	Map<String, String> fileMap=new HashMap<String, String>();
        	fileMap.put("file", localFileName);
        	String ret=formPost(urlStr, textMap, fileMap);
            System.out.println(ret);
            Map<String, String> result=getJsonObject(ret);
            if(StringUtils.hasText(result.get("ret")) && "0".equals(result.get("ret"))) {
            	if("[]".equals(result.get("features"))) {//没值
            		return 111;
                }else {//有值
                	return 200;
                }
            }
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        return 444;
    }
    
	/**
	 * @Title: formPost   
	 * @Description: 模拟from表单post提交   带文件和参数
	 * @author: JiangShuai
	 * @param: @param textMap   参数map
	 * @param: @param fileMap	文件map
	 * @param: @return      
	 * @return: String
	 */
    public static String formPost(String urlStr,Map<String, String> textMap, Map<String, String> fileMap) {  
    	//String urlStr="https://api.robotscloud.com/hsr/v3/face_detection";
        String res = "";  
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符    
        try {  
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();  
            conn.setConnectTimeout(5000);  
            conn.setReadTimeout(30000);  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");  
            conn.setRequestProperty("Connection", "Keep-Alive");  
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);  
            
            OutputStream out = new DataOutputStream(conn.getOutputStream());  
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();  
                Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry<String, String> entry = iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (!StringUtils.hasText(inputValue)) {  
                        continue;  
                    }  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");  
                    strBuf.append(inputValue);  
                }  
                out.write(strBuf.toString().getBytes());  
            }  
  
            // file    
            if (fileMap != null) {  
                Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry<String, String> entry = iter.next();  
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();  
                    if (!StringUtils.hasText(inputValue)) {  
                        continue;  
                    }  
                    File file = new File(inputValue);  
                    String filename = file.getName();  
                    
                    //自动获取文件类型  跟下面的二选一
                    /*MagicMatch match = Magic.getMagicMatch(file, false, true);  
                    String contentType = match.getMimeType();  
                    System.out.println("------>"+filename);*/
                    
                    //传值判断文件类型
                    String contentType="";
                    if (filename.endsWith(".png") || filename.endsWith(".PNG")) {
                        contentType = "image/png"; 
                    }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")
                        || filename.endsWith(".JPG") || filename.endsWith(".JPEG") || filename.endsWith(".JPE")) {
                         contentType = "image/jpeg";
                    }else if (filename.endsWith(".gif") || filename.endsWith(".GIF")) {
                         contentType = "image/gif";
                    }else if (filename.endsWith(".ico") || filename.endsWith(".ICO")) {
                        contentType = "image/image/x-icon";
                    }else {
                        contentType = "application/octet-stream";
                    }
  
                    StringBuffer strBuf = new StringBuffer();  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");  
  
                    out.write(strBuf.toString().getBytes());
  
                    DataInputStream in = new DataInputStream(new FileInputStream(file));  
                    int bytes = 0;  
                    byte[] bufferOut = new byte[1024];  
                    while ((bytes = in.read(bufferOut)) != -1) {  
                        out.write(bufferOut, 0, bytes);  
                    }  
                    in.close();  
                }  
            }  
  
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
            out.write(endData);  
            out.flush();  
            out.close();  
  
            // 读取返回数据    
            StringBuffer strBuf = new StringBuffer();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                strBuf.append(line).append("\n");  
            }  
            res = strBuf.toString();  
            reader.close();  
            reader = null;  
        } catch (Exception e) {  
            System.out.println("发送POST请求出错。" + urlStr);  
            e.printStackTrace();  
        } finally {  
            if (conn != null) {  
                conn.disconnect();  
                conn = null;  
            }  
        }  
        return res;  
    }
	
    /**
     * @Title: jsonStringToList   
     * @Description: json转List   不是固定格式的list或数组 
     * @author: JiangShuai
     * @param: @param rsContent
     * @param: @return
     * @param: @throws Exception      
     * @return: List<Map<String,String>>
     */
	public static List<Map<String, String>> jsonStringToList(String rsContent) throws Exception{
        JSONArray arry = JSONArray.fromObject(rsContent);
        //System.out.println("json字符串内容如下");
        //System.out.println(arry);
        List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
        for (int i = 0; i < arry.size(); i++){
            JSONObject jsonObject = arry.getJSONObject(i);
            Map<String, String> map = new HashMap<String, String>();
            for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();){
                String key = (String) iter.next();
                String value = jsonObject.get(key).toString();
                map.put(key, value);
            }
            rsList.add(map);
        }
        return rsList;
    }
	
	/**
	 * @Title: getJsonObject   
	 * @Description: json转map  固定格式的
	 * @author: JiangShuai
	 * @param: @param jsonStr
	 * @param: @return      
	 * @return: Map<String,String>
	 */
    public static Map<String, String> getJsonObject(String jsonStr){
    	Map<String, String> map=new HashMap<String, String>();
    	JSONObject json=JSONObject.fromObject(jsonStr);
        try {
            map.put("ret", json.get("ret")+"");
            map.put("msg", json.get("msg")+"");
            map.put("features", json.get("features")+"");
        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * @Title: encode   
     * @Description: Base64的加密解密
     * @author: JiangShuai
     * @param: @param bstr
     * @param: @return      
     * @return: String
     */
    @SuppressWarnings("restriction")
	public static String encode(byte[] bstr){    
        return new BASE64Encoder().encode(bstr);    
     }

    /**
     *  @Title: hamcsha1   
     * @Description: hamcsha1加密   
     * @author: JiangShuai
     * @param: @param data
     * @param: @param key
     * @param: @return      
     * @return: String
     */
    public static String hamcsha1(byte[] data, byte[] key) {
           try {
               SecretKeySpec signingKey = new SecretKeySpec(key, MAC_NAME);
               Mac mac = Mac.getInstance("HmacSHA1");
               mac.init(signingKey);
               return toHexString(mac.doFinal(data));
           } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
           } catch (InvalidKeyException e) {
                e.printStackTrace();
           }
          return null;
     }
     
    /**
     *  @Title: toHexString   
     * @Description: 转换为16进制  
     * @author: JiangShuai
     * @param: @param bytes
     * @param: @return      
     * @return: String
     */
    @SuppressWarnings("resource")
	public static String toHexString(byte[] bytes) {        
          Formatter formatter = new Formatter();             
          for (byte b : bytes) {
              formatter.format("%02x", b);
          }
          return formatter.toString();   
     }  
    
}
